package controller

import (
	"bluebell/logic"
	"bluebell/models"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"strconv"
)

func CreatePostHandler(ctx *gin.Context) {
	// 1. 获取参数及参数的校验
	param := new(models.Post)
	if err := ctx.ShouldBindJSON(param); err != nil {
		ResponseError(ctx, 400, "参数有误")
		return
	}
	UserID, err := getCurrentUserID(ctx)
	if err != nil {
		ResponseError(ctx, 403, "请重新登录")
	}
	param.AuthorID = UserID
	if err := logic.CreatePost(param); err != nil {
		zap.L().Error("logic.CreatePost failed", zap.Error(err))
		ResponseError(ctx, 400, "创建失败")
		return
	}
	ResponseSuccess(ctx, 200, "创建成功", nil)
}

func PostDetailHandler(ctx *gin.Context) {
	idStr := ctx.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		ResponseError(ctx, 400, "参数有误")
		return
	}
	var post *models.Post
	post, err = logic.GetPostDetail(id)
	if err != nil {
		ResponseError(ctx, 400, "未查询到数据")
		return
	}
	ResponseSuccess(ctx, 200, "ok", post)
}

// PostListHandler 获取帖子列表(无条件)
// @Summary 获取帖子列表接口
// @Description 可按社区按时间或分数排序查询帖子列表接口
// @Tags 帖子相关接口
// @Accept application/json
// @Produce application/json
// @Param Authorization header string false "Bearer 用户令牌"
// @Param object query models.ParamPostList false "查询参数"
// @Security ApiKeyAuth
// @Success 200 {object} models.ParamPostList
// @Router /post [get]
func PostListHandler(ctx *gin.Context) {
	page, limit := getPageInfo(ctx)
	posts, err := logic.GetPostList(page, limit)
	if err != nil {
		ResponseError(ctx, 400, "未查询到数据")
		return
	}
	ResponseSuccess(ctx, 200, "ok", posts)
}

// PostListByFactorHandler PostListHandler 获取帖子列表(有条件)
func PostListByFactorHandler(ctx *gin.Context) {
	page, limit := getPageInfo(ctx)
	param := &models.ParamPostList{
		Page:  page,
		Limit: limit,
		Order: "time",
	}

	data, err := logic.GetPostListByFactor(param)
	if err != nil {
		ResponseError(ctx, 400, "未查询到数据")
		return
	}
	ResponseSuccess(ctx, 200, "ok", data)
}

func CommunityPostListHandler(ctx *gin.Context) {
	page, limit := getPageInfo(ctx)
	communityIdStr := ctx.Query("community_id")
	communityId, err := strconv.ParseInt(communityIdStr, 10, 64)
	if err != nil {
		ResponseError(ctx, 400, "未查询到数据")
	}
	param := &models.ParamCommunityPostList{
		Page:        page,
		Limit:       limit,
		Order:       "time",
		CommunityID: communityId,
	}
	var data []*models.ResPostDetail
	data, err = logic.GetCommunityPostList(param)
	if err != nil {
		ResponseError(ctx, 400, "未查询到数据")
		return
	}
	ResponseSuccess(ctx, 200, "ok", data)
}
